function S = myprepsimulate2(This,S,IAlt)
% myprepsimulate2  [Not a public function] Prepare i-th simulation round.
%
% Backed IRIS function.
% No help provided.

% -IRIS Toolbox.
% -Copyright (c) 2007-2015 IRIS Solutions Team.

%--------------------------------------------------------------------------

ne = sum(This.nametype == 3);
nn = sum(This.IxNonlin);
lastEa = S.LastEa;
lastEndgA = S.LastEndgA;
nPerNonlin = S.NPerNonlin;

% Forward expansion needed
%--------------------------
S.TPlusK = max([1,lastEa,lastEndgA,nPerNonlin]) - 1;

% Loop-dependent fields
%-----------------------
% Current values of parameters and steady states.
S.Assign = This.Assign(1,:,IAlt);
S.StdCorr = This.stdcorr(1,:,IAlt);

% Solution matrices.
S.T = This.solution{1}(:,:,IAlt);
S.R = This.solution{2}(:,:,IAlt);
S.K = This.solution{3}(:,:,IAlt);
S.Z = This.solution{4}(:,:,IAlt);
S.H = This.solution{5}(:,:,IAlt);
S.D = This.solution{6}(:,:,IAlt);
S.U = This.solution{7}(:,:,IAlt);

% Solution expansion matrices.
S.Expand = cell(size(This.Expand));
for ii = 1 : numel(S.Expand)
    S.Expand{ii} = This.Expand{ii}(:,:,IAlt);
end

nPerMax = S.NPer;
% Effect of nonlinear add-factors in selective nonlinear simulations.
if isequal(S.Method,'selective')
    nPerMax = nPerMax + S.NPerNonlin - 1;
    S.Q = This.solution{8}(:,:,IAlt);
end

% Get steady state lines that will be added to simulated paths to evaluate
% nonlinear equations; the steady state lines include pre-sample init cond.
if isequal(S.Method,'selective') || isequal(S.Method,'global')
    if S.IsDeviation && S.IsAddSstate
        isDelog = false;
        S.XBar = mytrendarray(This,IAlt, ...
            isDelog,This.solutionid{2},0:nPerMax);
        S.YBar = mytrendarray(This,IAlt, ...
            isDelog,This.solutionid{1},0:nPerMax);
    end
end

if S.IsUpdate ...
        || isequal(S.Method,'selective') || isequal(S.Method,'global')
    % Steady state references.
    minT = This.Shift(1);
    maxT = This.Shift(end);
    S.MinT = minT;
    isDelog = true;
    id = 1 : length(This.name);
    tVec = (1+minT) : (nPerMax+maxT);
    S.L = mytrendarray(This,IAlt,isDelog,id,tVec);
end

% Expand solution forward up to t+k if needed.
if S.TPlusK > 0
    if isequal(S.Method,'selective') && (ne > 0 || nn > 0)
        % Expand solution forward to t+k for both shocks and non-linear
        % add-factors.
        [S.R,S.Q] = model.myexpand(S.R,S.Q,S.TPlusK,S.Expand{1:6});
    elseif ne > 0
        % Expand solution forward to t+k for shocks only.
        S.R = model.myexpand(S.R,[],S.TPlusK,S.Expand{1:5},[]);
    end
end

end
